import {createSession, deleteSession, chatWithBot} from "../../utils/agent.js"
import {getUserInfo} from "../../utils/auth.js"
var aiMessage = {}

Page({
  data: {
    messages: [
      {
        id: 1,
        role: 'ai',
        content: '您好！我是您的AI助手，有什么可以帮助您的吗？',
        time: '刚刚',
        typing: false
      }
    ],
    inputValue: '',
    scrollTop: 0,
    conversationId: "",
    updateTimer: true,
    sendIcon: "../../images/usend.png",
    aiAvatar: "../../images/robot.png",
    avatarUrl: "../../images/user.png"
  },
  //页面加载时
  onLoad() {
    createSession().then(res=>{
      console.log(res)
      this.setData({
        conversationId: res.data.id
      })
    })
  },
  onShow(){
    this.setData({
      avatarUrl: getUserInfo().avatarUrl
    })
  },
  //页面删除时
  onUnload(){
    deleteSession(this.data.conversationId)
  },
 
  onInput: function(e) {
    if(e.detail.value !== ""){
      this.setData({
        sendIcon: "../../images/send.png",
        inputValue: e.detail.value,
      })
    }else{
      this.setData({
        sendIcon: "../../images/usend.png"
      })
    }
  },

  sendMessage: function() {
    const inputValue = this.data.inputValue.trim();
    if (!inputValue) return;
    // 添加用户消息
    const userMessage = {
      id: Date.now(),
      role: 'user',
      content: inputValue,
      time: this.getCurrentTime(),
      typing: false
    };
    this.setData({
      messages: [...this.data.messages, userMessage],
      sendIcon: "../../images/usend.png",
      inputValue: ''
    });
    // 滚动到底部
    this.scrollToBottom();
    if(this.data.conversationId){
      const requestTask = chatWithBot(this.data.conversationId, [{
        "role": "user",
        "content": userMessage.content,
        "content_type": "text"
      }])
      aiMessage = {
        id: Date.now(),
        role: "ai",
        content: "",
        time: this.getCurrentTime(),
        url: "",
        typing: true
      }
      if (requestTask?.onChunkReceived) {
        requestTask.onChunkReceived(this.handleChunkData);
      } else {
        // 不支持流式，降级为普通请求
        console.log(aiMessage)
      }
    }
  },
  
  handleChunkData (res) {
    try {
      let rawStr = "";
      // 微信小程序ArrayBuffer转字符串
      rawStr = this.arrayBufferToString(res.data)
      // 提取JSON内容
      const chunkJson = rawStr.split("\n\n");

      chunkJson.forEach(element => {
        const chunkAnswer = element.split("data:");
        // 创建对话时，新增数组
        if(chunkAnswer[0].includes("created")){
          this.setData({
            messages: [...this.data.messages, aiMessage]
          })
        }
        // 返回消息片段时
        if(chunkAnswer[0].includes("delta")){
          const rawData = JSON.parse(chunkAnswer[1]);
          aiMessage.content = aiMessage.content + rawData.content
          this.updateLastMessageSafe(this.data.messages, aiMessage)
        }
        // 回复完成时
        if(chunkAnswer[0].includes("complete")){
          aiMessage.typing = false
          const rawData = JSON.parse(chunkAnswer[1]);
          console.log(rawData)
          if(rawData.content_type === "card"){
            var data = JSON.parse(rawData.content)
            data = JSON.parse(data.data)
            var elements = Object.values(data.elements)
            var variables = Object.values(data.variables)
            for(var i=0; i< elements.length;i++){
              if(elements[i].type.includes("Text")){
                aiMessage.content = variables[i].defaultValue
              }
              if(elements[i].type.includes("NewImage")){
                aiMessage.url = variables[i].defaultValue
              }
            }
          }else {
            this.updateLastMessageSafe(this.data.messages, aiMessage)
          }

          // aiMessage.url = getUserInfo().avatarUrl 西安绿地中心A座基本情况
          
        }
        this.scrollToBottom()
      });
    } catch (e) {
      console.error("数据处理异常:", e);
    }
  },

// 更安全的方式
  updateLastMessageSafe(messages, newMessage) {
    const lastIndex = messages.length - 1;
    // 创建新对象，保持不可变性
    const updatedMessages = [...messages];
    updatedMessages[lastIndex] = newMessage;
    this.setData({
      messages: updatedMessages
    });
  },

  getCurrentTime: function() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  },

  scrollToBottom: function() {
    // 使用setTimeout确保在渲染完成后滚动
    setTimeout(() => {
      this.setData({
        scrollTop: 99999 // 设置一个足够大的值确保滚动到底部
      });
    }, 100);
  },

  // 通用ArrayBuffer转字符串方法
  arrayBufferToString(buffer) {
    // 将ArrayBuffer转为Uint8Array
    const uint8Array = new Uint8Array(buffer);
    
    // 方案1: 使用TextDecoder（推荐，支持中文）
    if (typeof TextDecoder !== 'undefined') {
      const decoder = new TextDecoder('utf-8');
      return decoder.decode(uint8Array);
    }
    
    // 方案2: 手动解码（兼容性方案）
    let result = '';
    for (let i = 0; i < uint8Array.length; i++) {
      result += String.fromCharCode(uint8Array[i]);
    }
    
    // 尝试UTF-8解码，如果失败则返回原始字符串
    try {
      return decodeURIComponent(escape(result));
    } catch (e) {
      return result;
    }
  },
})